﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using CMISLibrary.Libraries;
using busDanhMuc;
using EntitiesDanhMuc;
using BaocaoNPC.common;
using OutlookBar;
using System.Data;
using OutlookBar.Components;
using CustomControl;
using AvalonDock;
using CMISLibrary.Libraries;


namespace NPCUS_DanhMuc.Usercontrols
{
    /// <summary>
    /// Interaction logic for NPC_MENUOFUSER.xaml
    /// </summary>
    public partial class NPC_MENUOFUSER : UserControl
    {

        DataSet dsUserName = new DataSet();
        DataSet DsUSER = new EntitiesDanhMuc.dsS_USER();
        DataTable dtHienThi = new DataTable();
        private string strMa_dviqly = NPCUS_DanhMuc.Pglobal.strMa_dviqly != "" && NPCUS_DanhMuc.Pglobal.strMa_dviqly != null ? NPCUS_DanhMuc.Pglobal.strMa_dviqly : "PA";
        string maloi;        
        private int intCurrIndexR = 0;
        private DataRowView drvR = null;
        private string TRANGTHAINUT = "";

        TreeViewItem itsel = new TreeViewItem();
        TreeViewItem itselGoc = new TreeViewItem();
        TreeViewItem itselUser = new TreeViewItem();

        private DataSet dsResultTREE;
        private object dummyNode = null;

        DataSet dsChuyenDL;
        DataSet dsLuuCaygoc;
        DataSet dsXoaItems;
        DataSet dsCayUserGoc;
        DataSet dsCayUserHtai;
        DataSet dsTreeTemp;
        DataSet dsInserttoNPC_MENUOFUSER;
        DataSet dsNPC_LIBRARY_Entity;
        DataSet dsNPC_MENU_Entity;
        DataSet dsNPC_MENUOFUSER_Entity;
        DataSet dsNPC_MENUOFUSER_get;
        DataSet dsSmenu_toInsert;
        DataSet dsSmenu_toDel;
        DataSet dsColor;
        cls_NPC_LIBRARY clsNPC_LIBRARY = new cls_NPC_LIBRARY();
        cls_NPC_MENU clsNPC_MENU = new cls_NPC_MENU();
        cls_NPC_MENUOFUSER clsmenuofuser = new cls_NPC_MENUOFUSER();

        string id = "";
        string ten = "";
        string dienthoai = "";
        string strBtnClick = "";
        string strError = "";
        string strFind = "";
        int intDongFocus = 0;
        int intIDdong = 0;
        long intLIBID = -2;
        long intMENUIDtreeItemSel = -2;
        long intMENUIDuser = -2;
        long intPARENTMENUID = -2;
        long intMENUID = -2;
        long intUserID = -2;
        long intMenuidInsertOrDel = -1;
        long intMENUOFUSERIdInsertOrDel = -1;

        //DataRow[] drArr;


        public NPC_MENUOFUSER()
        {
            InitializeComponent();

            dsTreeTemp = new EntitiesDanhMuc.NPC_MENU();
            dsXoaItems = new EntitiesDanhMuc.NPC_MENU();
            dsNPC_MENUOFUSER_Entity = new EntitiesDanhMuc.NPC_MENUOFUSER();
            dsInserttoNPC_MENUOFUSER = new EntitiesDanhMuc.NPC_MENUOFUSER();

            btnGhi.IsEnabled = false;
            btnTieptuc.IsEnabled = true;
            btnThem.IsEnabled = false;
            btnXoa.IsEnabled = false;
            btnChon.IsEnabled = false;
        }

        private void setCurrentData()
        {
            DataRowView drv = dgrDanhSach.SelectedItem as DataRowView;

            if (drv != null)
            {
                if (strBtnClick == "btnChon")
                {

                }
                else
                {
                    txtUSERNAME.Text = drv.Row["USERNAME"].ToString();

                    txtFULLNAME.Text = drv.Row["FULLNAME"].ToString();

                    txtEMAIL.Text = drv.Row["EMAIL"].ToString();

                    btnChon.IsEnabled = true;
                }
            }
        }

        private void setEntity(string strBtnClick)
        {
            try
            {
                dsNPC_MENUOFUSER_Entity.Tables["NPC_MENUOFUSER"].Clear();
                DataRow dr = dsNPC_MENUOFUSER_Entity.Tables["NPC_MENUOFUSER"].NewRow();
                switch (strBtnClick)
                {
                    case "btnGhi":
                        dr["SUBDIVISIONID"] = NPCUS_DanhMuc.Pglobal.strMa_dviqly;
                        dr["MENUOFUSERID"] = intMENUOFUSERIdInsertOrDel;
                        dr["USERID"] = intUserID;
                        dr["MENUID"] = intMenuidInsertOrDel;
                        dr["CREATEDDATE"] = DateTime.Now.Date;
                        dr["CREATEDBY"] = "Admin";

                        break;


                    case "btnXoa":
                        dr["SUBDIVISIONID"] = NPCUS_DanhMuc.Pglobal.strMa_dviqly;
                        dr["MENUOFUSERID"] = intMENUOFUSERIdInsertOrDel;
                        dr["USERID"] = intUserID;
                        dr["MENUID"] = intMenuidInsertOrDel;
                        dr["CREATEDDATE"] = DateTime.Now.Date;
                        dr["CREATEDBY"] = "Admin";

                        break;
                    /*
           case "btnTimKiem":
               dr["SUBDIVISIONID"] = "PA";

               dr["LIBID"] = -1;

               if (txtLIBNAME_S.Text.Trim().ToString() != string.Empty)
               {
                   dr["LIBNAME"] = txtLIBNAME_S.Text.Trim().ToString();
               }
               else
               {
                   dr["LIBNAME"] = " ";
               }

               dr["NAMESPACE"] = " ";

               if (txtASSEMBLYNAME_S.Text.Trim().ToString() != string.Empty)
               {
                   dr["ASSEMBLYNAME"] = txtASSEMBLYNAME_S.Text.Trim().ToString();
               }
               else
               {
                   dr["ASSEMBLYNAME"] = " ";
               }

               dr["PRIORITY"] = 3;

               dr["STATE"] = 1;

               dr["CREATEDDATE"] = DateTime.Now.Date;

               dr["CREATEDBY"] = "Admin";

               break;
           case "btnThemMoi":

               break;
                * */
                }
                dsNPC_MENUOFUSER_Entity.Tables["NPC_MENUOFUSER"].Rows.Add(dr);
                dsNPC_MENUOFUSER_Entity.AcceptChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void GetData_InserttoNPC_MENUOFUSER() // so sánh cây User hiện tại với cây User gốc -> có thêm chức năng -> lấy item vào dsCayUserGoc
        {
            try
            {
                if (dsCayUserGoc != null && dsCayUserGoc.Tables[0].Rows.Count > 0 && dsCayUserHtai != null && dsCayUserHtai.Tables[0].Rows.Count > 0)
                {
                    dsSmenu_toInsert = dsCayUserGoc.Clone();

                    for (int i = 0; i < dsCayUserHtai.Tables[0].Rows.Count; i++)
                    {
                        long menuid = Convert.ToInt64(dsCayUserHtai.Tables[0].Rows[i]["MENUID"]);
                        DataRow[] drArr = dsCayUserGoc.Tables[0].Select("MENUID = '" + menuid.ToString() + "'");
                        if (drArr.Count() < 1)
                        {
                            dsSmenu_toInsert.Tables[0].ImportRow(dsCayUserHtai.Tables[0].Rows[i]);
                        }
                    }
                }

                if (dsCayUserGoc == null || dsCayUserGoc.Tables[0].Rows.Count < 1)
                {
                    dsSmenu_toInsert = dsCayUserHtai.Copy();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void GetData_toDelNPC_MENUOFUSER() // so sánh cây User Gốc với cây User hiện tại -> ko có chức năng -> xóa item ở dsCayUserGoc
        {
            try
            {
                if (dsCayUserGoc != null && dsCayUserGoc.Tables[0].Rows.Count > 0)
                {
                    dsSmenu_toDel = dsCayUserGoc.Clone();
                    for (int i = 0; i < dsCayUserGoc.Tables[0].Rows.Count; i++)
                    {
                        long menuid = Convert.ToInt64(dsCayUserGoc.Tables[0].Rows[i]["MENUID"]);
                        DataRow[] drArr = dsCayUserHtai.Tables[0].Select("MENUID = '" + menuid.ToString() + "'");
                        if (drArr.Count() < 1)
                        {
                            dsSmenu_toDel.Tables[0].ImportRow(dsCayUserGoc.Tables[0].Rows[i]);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void Get_cayMenuGoc()
        {
            try
            {
                cls_NPC_MENU cls = new cls_NPC_MENU();

                dsResultTREE = new DataSet();
                dsResultTREE = GlobalServices.Service_NPCUS.select_NPC_MENU_All();                

                dsResultTREE_vs_dsCayUserHtai();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void Fill_Data_Tree()
        {
            try
            {
                cls_NPC_MENU cls = new cls_NPC_MENU();

                TreeViewItem root = new TreeViewItem();
                //TreeNode node = null;
                dsResultTREE = new DataSet();
                dsResultTREE = GlobalServices.Service_NPCUS.select_NPC_MENU_All();
                

                //Get_cayMenuGoc();
                dsResultTREE_vs_dsCayUserHtai();

                this.TvGoc.Items.Clear(); // xoa tree tru?c khi d? d? li?u m?i
                if (dsResultTREE == null)
                {
                    MessageBox.Show(" Không có phần tử nào trên cây !");
                    return;
                }
                DataView dv = new DataView(dsResultTREE.Tables[0]);
                //HeaderToImageConverter.Instance.ds = dsResultTREE.Copy();
                if (dv.Count == 0) // không có d? li?u không dua ra tree
                {
                    MessageBox.Show(" Không có phần tử nào trên cây !");
                    return;
                }
                //btnThem.IsEnabled = true;
                //btnXoa.IsEnabled = false;
                dv.Sort = "PARENTMENUID,ORDERNUMBER";

                foreach (DataRowView dr in dv)
                {
                    TreeViewItem item = new TreeViewItem();
                    if (dr["PARENTMENUID"].ToString() == string.Empty)
                    {
                        if (dsColor != null && dsColor.Tables[0].Rows.Count > 0)
                        {
                            DataRow[] drArr = dsColor.Tables[0].Select("MENUID = '" + dr["MENUID"].ToString() + "'");
                            if (drArr.Count() > 0)
                            {
                                item.Foreground = Brushes.Red;
                            }
                        }

                        item.Header = dr["HEADER"].ToString();
                        //if (dr["TTRANG_DONGCAT"].ToString() == "0") item.Foreground = Brushes.Red;
                        //if (dr["TTRANG_DONGCAT"].ToString == "0") item.Foreground = Brushes.;
                        item.Tag = dr["MENUID"].ToString();
                        item.FontWeight = FontWeights.Normal;
                        item.Items.Add(dummyNode);
                        item.Expanded += new RoutedEventHandler(folder_Expanded);
                        dsResultTREE.Tables[0].DefaultView.RowFilter = "PARENTMENUID = '" + dr["MENUID"].ToString() + "'";
                        //if (dsResultTREE.Tables[0].DefaultView.Count == 0) 
                        item.IsExpanded = true;
                        TvGoc.Items.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
        }
        private void folder_Expanded(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = (TreeViewItem)sender;
            DataView dv = new DataView(dsResultTREE.Tables[0]);
            dv.Sort = "PARENTMENUID,ORDERNUMBER";
            if (item.Items.Count == 1 && item.Items[0] == dummyNode)
            {
                item.Items.Clear();
                try
                {
                    foreach (DataRowView dr in dv)
                    {

                        TreeViewItem subitem = new TreeViewItem();
                        if (dr["PARENTMENUID"].ToString() == item.Tag.ToString())
                        {
                            subitem.Header = dr["HEADER"].ToString();
                            subitem.Tag = dr["MENUID"].ToString();
                            //if (dr["TTRANG_DONGCAT"].ToString() == "0") subitem.Foreground = Brushes.Red;
                            subitem.FontWeight = FontWeights.Normal;
                            subitem.Items.Add(dummyNode);
                            subitem.Expanded += new RoutedEventHandler(folder_Expanded);
                            dsResultTREE.Tables[0].DefaultView.RowFilter = "PARENTMENUID = '" + dr["MENUID"].ToString() + "'";
                            if (dsResultTREE.Tables[0].DefaultView.Count == 0) subitem.IsExpanded = true;

                            if (dsColor != null && dsColor.Tables[0].Rows.Count > 0)
                            {
                                DataRow[] drArr = dsColor.Tables[0].Select("MENUID = '" + dr["MENUID"].ToString() + "'");
                                if (drArr.Count() > 0)
                                {
                                    subitem.Foreground = Brushes.Red;
                                }
                            }
                            item.Items.Add(subitem);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    return;
                }
            }
        }



        private void Fill_Data_Tree_User(DataSet dsNguon)
        {
            try
            {
                dsChuyenDL = new DataSet();
                dsChuyenDL = dsNguon.Copy();

                TreeViewItem root = new TreeViewItem();
                //TreeNode node = null;                

                this.TvUser.Items.Clear(); // xoa tree tru?c khi d? d? li?u m?i
                if (dsChuyenDL == null)
                {
                    MessageBox.Show(" Không có phần tử nào trên cây !");
                    return;
                }
                DataView dv = new DataView(dsChuyenDL.Tables[0]);
                //HeaderToImageConverter.Instance.ds = dsResultTREE.Copy();
                if (dv.Count == 0) // không có d? li?u không dua ra tree
                {
                    MessageBox.Show(" Không có phần tử nào trên cây !");
                    return;
                }
                //btnXoa.IsEnabled = true;
                dv.Sort = "PARENTMENUID,ORDERNUMBER";

                foreach (DataRowView dr in dv)
                {
                    TreeViewItem item = new TreeViewItem();
                    if (dr["PARENTMENUID"].ToString() == string.Empty)
                    {
                        item.Header = dr["HEADER"].ToString();
                        //if (dr["TTRANG_DONGCAT"].ToString() == "0") item.Foreground = Brushes.Red;
                        //if (dr["TTRANG_DONGCAT"].ToString == "0") item.Foreground = Brushes.;
                        item.Tag = dr["MENUID"].ToString();
                        item.FontWeight = FontWeights.Normal;
                        item.Items.Add(dummyNode);
                        item.Expanded += new RoutedEventHandler(folder_Expanded_User);
                        dsChuyenDL.Tables[0].DefaultView.RowFilter = "PARENTMENUID = '" + dr["MENUID"].ToString() + "'";
                        //if (dsResultTREE.Tables[0].DefaultView.Count == 0) 
                        item.IsExpanded = true;
                        TvUser.Items.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
        }

        private void folder_Expanded_User(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = (TreeViewItem)sender;
            DataView dv = new DataView(dsChuyenDL.Tables[0]);
            dv.Sort = "PARENTMENUID,ORDERNUMBER";
            if (item.Items.Count == 1 && item.Items[0] == dummyNode)
            {
                item.Items.Clear();
                try
                {
                    foreach (DataRowView dr in dv)
                    {
                        TreeViewItem subitem = new TreeViewItem();
                        if (dr["PARENTMENUID"].ToString() == item.Tag.ToString())
                        {
                            subitem.Header = dr["HEADER"].ToString();
                            subitem.Tag = dr["MENUID"].ToString();
                            //if (dr["TTRANG_DONGCAT"].ToString() == "0") subitem.Foreground = Brushes.Red;
                            subitem.FontWeight = FontWeights.Normal;
                            subitem.Items.Add(dummyNode);
                            subitem.Expanded += new RoutedEventHandler(folder_Expanded_User);
                            dsChuyenDL.Tables[0].DefaultView.RowFilter = "PARENTMENUID = '" + dr["MENUID"].ToString() + "'";
                            if (dsChuyenDL.Tables[0].DefaultView.Count == 0) subitem.IsExpanded = true;
                            item.Items.Add(subitem);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    return;
                }
            }
        }

        private void txtSearchTenDangNhap_GotFocus(object sender, RoutedEventArgs e)
        {

        }

        private void txtSearchTenDangNhap_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void txtSearchTenDayDu_GotFocus(object sender, RoutedEventArgs e)
        {

        }

        private void txtSearchTenDayDu_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void btnTimKiem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //SetStatus("THONGBAOBATDAU", btnTimKiem, "Đang lấy dữ liệu ...");
                dsUserName = GlobalServices.Service_NPCUS.GET_USERNAME(strMa_dviqly, ref maloi);               
                
                if (dsUserName == null)
                {
                    //SetStatus("THONGBAOLOI", btnTimKiem, "Không tìm thấy dữ liệu");
                    dgrDanhSach.ItemsSource = null;
                    //xoa_text();
                    return;
                }
                DataTable dt = dsUserName.Tables[0] as DataTable;
                dtHienThi = new DataTable();
                dt.DefaultView.RowFilter = "USERNAME LIKE '%" + txtSearchTenDangNhap.Text.Trim().ToUpper() + "%' and FULLNAME LIKE '%" + txtSearchTenDayDu.Text.Trim().ToUpper() + "%'";
                if (dt.DefaultView.Count > 0)
                {
                    dtHienThi = dt.Select("USERNAME LIKE '%" + txtSearchTenDangNhap.Text.Trim().ToUpper() + "%' and FULLNAME LIKE '%" + txtSearchTenDayDu.Text.Trim().ToUpper() + "%'").CopyToDataTable();
                    dgrDanhSach.ItemsSource = dtHienThi.DefaultView;
                    dgrDanhSach.SelectedIndex = 0;
                }
                else
                {
                    //SetStatus("THONGBAOLOI", btnTimKiem, "Không tìm thấy dữ liệu");
                    dgrDanhSach.ItemsSource = null;
                    //xoa_text(); return;
                }
                //lbltso.Content = "Tổng : " + dgrDanhSach.Items.Count;
                //SetStatus("THONGBAONULL", btnTimKiem, "");
            }
            catch
            { //SetStatus("THONGBAOLOI", btnTimKiem, maloi); 
                MessageBox.Show(maloi);
            }
        }

        private void dgrDanhSach_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                setCurrentData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void Refresh()
        {
            try
            {
                TvGoc.Items.Clear();
                TvUser.Items.Clear();

                dsResultTREE.Clear();
                dsCayUserGoc.Clear();
                dsCayUserHtai.Clear();
                dsChuyenDL.Clear();
                dsNPC_MENUOFUSER_get.Clear();
                dsSmenu_toDel.Clear();
                dsSmenu_toInsert.Clear();
            }
            catch
            { }
        }

        private void btnTieptuc_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Refresh();
                btnGhi.IsEnabled = false;
                btnChon.IsEnabled = true;

            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
            }
        }

        private void btnGhi_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.Wait;

                bool checkInsert = false;

                GetData_InserttoNPC_MENUOFUSER();
                GetData_toDelNPC_MENUOFUSER();

                #region Ghi du lieu
                if (dsSmenu_toInsert != null && dsSmenu_toInsert.Tables[0].Rows.Count > 0) // ghi du lieu
                {
                    for (int i = 0; i < dsSmenu_toInsert.Tables[0].Rows.Count; i++)
                    {
                        // ======= Thêm mới -> lấy nextSeq ======
                        if (strBtnClick == "btnChon")
                        {
                            long nextSeq = 0;                            
                            nextSeq = GlobalServices.Service_NPCUS.GetNextSequence_menuofuser(ref strError);  
                            intMENUOFUSERIdInsertOrDel = nextSeq;
                            intMenuidInsertOrDel = Convert.ToInt64(dsSmenu_toInsert.Tables[0].Rows[i]["MENUID"]);
                        }

                        // ======== Them moi -> kiem tra PK ========
                        //if (strBtnClick == "btnThemMoi")
                        //{
                        //    if (checkPK() == true)
                        //    {
                        //        this.Cursor = null;
                        //        MessageBox.Show("ID đã tồn tại!");
                        //        return;
                        //    }
                        //}

                        setEntity("btnGhi");
                        checkInsert = GlobalServices.Service_NPCUS.insert_NPC_MENUOFUSER(dsNPC_MENUOFUSER_Entity, ref strError);
                       
                        // ===== Kiem tra Insert , Update thanh cong ? ===
                        if (checkInsert == true)
                        {
                            this.Cursor = null;

                        }
                        else
                        {
                            this.Cursor = null;
                            MessageBox.Show("Không ghi được dữ liệu !");
                            break;
                        }
                    }
                }
                #endregion

                #region Xoa du lieu

                if (dsSmenu_toDel != null && dsSmenu_toDel.Tables[0].Rows.Count > 0)
                {
                    for (int ii = 0; ii < dsSmenu_toDel.Tables[0].Rows.Count; ii++)
                    {

                        //intMENUOFUSERIdInsertOrDel = Convert.ToInt64(dsSmenu_toDel.Tables[0].Rows[ii]["MENUID"]);
                        intMenuidInsertOrDel = Convert.ToInt64(dsSmenu_toDel.Tables[0].Rows[ii]["MENUID"]);

                        DataRow[] drArr = dsNPC_MENUOFUSER_get.Tables[0].Select("MENUID = '" + intMenuidInsertOrDel + "'");
                        if (drArr.Count() > 0)
                        {
                            intMENUOFUSERIdInsertOrDel = Convert.ToInt64(drArr[0]["MENUOFUSERID"]);
                        }
                        else
                        {
                            intMENUOFUSERIdInsertOrDel = 0;
                        }

                        setEntity("btnXoa");
                        checkInsert = GlobalServices.Service_NPCUS.delete_NPC_MENUOFUSER(dsNPC_MENUOFUSER_Entity, ref strError);
                        
                        // ===== Kiem tra Delete thanh cong ? ===
                        if (checkInsert == true)
                        {
                            this.Cursor = null;
                        }
                        else
                        {
                            this.Cursor = null;
                            MessageBox.Show("Không xóa được dữ liệu !");
                            break;
                        }
                    }
                }

                if (checkInsert == true)
                {
                    Refresh();
                    MessageBox.Show("Ghi thành công !");
                }

                #endregion

                btnXoa.IsEnabled = true;
                btnGhi.IsEnabled = false;
                btnTimKiem.IsEnabled = true;

                strBtnClick = "";
                this.Cursor = null;


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void btnChon_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                cls_NPC_MENU cls = new cls_NPC_MENU();

                dsResultTREE = new DataSet();
                dsResultTREE = GlobalServices.Service_NPCUS.select_NPC_MENU_All();                

                #region Lay cay cua User
                DataRowView drv = dgrDanhSach.SelectedItem as DataRowView;
                if (drv != null)
                {
                    string strSUB = drv["MA_DVIQLY"].ToString();
                    intUserID = Convert.ToInt64(drv["USERID"]);
                    dsNPC_MENUOFUSER_get = GlobalServices.Service_NPCUS.select_NPC_MENUOFUSER_by_USERID(strSUB, intUserID);
                   
                    if (dsNPC_MENUOFUSER_get != null && dsNPC_MENUOFUSER_get.Tables[0].Rows.Count > 0)
                    {
                        GetdataTree_from_menuofuser();

                        dsCayUserHtai = dsCayUserGoc.Copy();
                        Fill_Data_Tree_User(dsCayUserGoc);
                    }
                }
                #endregion

                // Lấy cây đầy đủ của hệ thống
                Fill_Data_Tree();

                strBtnClick = "btnChon";

                btnChon.IsEnabled = false;
                btnGhi.IsEnabled = true;
                btnTieptuc.IsEnabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void GetdataTree_from_menuofuser()
        {
            try
            {
                dsCayUserGoc = dsResultTREE.Clone();
                for (int i = 0; i < dsResultTREE.Tables[0].Rows.Count; i++)
                {
                    string strmenuid = dsResultTREE.Tables[0].Rows[i]["MENUID"].ToString();
                    DataRow[] drArr = dsNPC_MENUOFUSER_get.Tables[0].Select("MENUID = '" + strmenuid + "'");
                    if (drArr.Count() > 0)
                    {
                        dsCayUserGoc.Tables[0].ImportRow(dsResultTREE.Tables[0].Rows[i]);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void Find_Parent(long intmenu)
        {
            try
            {
                DataRow[] drArr;
                drArr = dsResultTREE.Tables[0].Select("MENUID = '" + intmenu.ToString() + "'");

                DataTable dt = new DataTable();

                if (drArr.Count() > 0)
                {
                    dt = drArr.CopyToDataTable();
                    if (dt.Rows[0]["PARENTMENUID"].ToString() != string.Empty)
                    {
                        intPARENTMENUID = Convert.ToInt64(dt.Rows[0]["PARENTMENUID"].ToString());

                        //menu chưa có trong dsTreeTemp -> Import
                        if (dsTreeTemp.Tables[0].Select("MENUID = '" + intmenu.ToString() + "'").Count() < 1)
                        {
                            dsTreeTemp.Tables[0].ImportRow(dt.Rows[0]);
                        }
                        Find_Parent(intPARENTMENUID);
                    }
                    else
                    {
                        dsTreeTemp.Tables[0].ImportRow(dt.Rows[0]);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void Find_Children(long intmenu)
        {
            try
            {
                DataRow[] drArr;
                drArr = dsResultTREE.Tables[0].Select("PARENTMENUID = '" + intmenu.ToString() + "'");

                DataTable dt = new DataTable();

                if (drArr.Count() > 0)
                {
                    dt = drArr.CopyToDataTable();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["MENUID"].ToString() != string.Empty)
                        {
                            intMENUID = Convert.ToInt64(dt.Rows[i]["MENUID"].ToString());

                            //menu chưa có trong dsTreeTemp -> Import
                            if (dsTreeTemp.Tables[0].Select("MENUID = '" + intMENUID + "'").Count() < 1)
                            {
                                dsTreeTemp.Tables[0].ImportRow(dt.Rows[i]);
                            }
                            Find_Children(intMENUID);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void Get_Childrens_to_del(long intmenu) // lấy danh sách item để xóa
        {
            try
            {
                DataRow[] drArr;
                drArr = dsResultTREE.Tables[0].Select("PARENTMENUID = '" + intmenu.ToString() + "'");

                DataTable dt = new DataTable();

                if (drArr.Count() > 0)
                {
                    dt = drArr.CopyToDataTable();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["MENUID"].ToString() != string.Empty)
                        {
                            intMENUID = Convert.ToInt64(dt.Rows[i]["MENUID"].ToString());

                            //menu chưa có trong dsTreeTemp -> Import                            
                            dsXoaItems.Tables[0].ImportRow(dt.Rows[i]);

                            Get_Childrens_to_del(intMENUID);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void Del_childrens() //xóa item
        {
            try
            {
                for (int i = 0; i < dsXoaItems.Tables[0].Rows.Count; i++)
                {
                    string menuid = dsXoaItems.Tables[0].Rows[i]["MENUID"].ToString();
                    for (int ii = 0; ii < dsCayUserHtai.Tables[0].Rows.Count; ii++)
                        if (dsCayUserHtai.Tables[0].Rows[ii]["MENUID"].ToString() == menuid)
                        {
                            dsCayUserHtai.Tables[0].Rows[ii].Delete();
                            dsCayUserHtai.Tables[0].AcceptChanges();
                        }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void dsTreeTemp_vs_dsCayUserHtai() // lấy thêm item 
        {
            try
            {
                if (dsCayUserHtai == null || dsCayUserHtai.Tables[0].Rows.Count < 1)
                {
                    dsCayUserHtai = dsTreeTemp.Copy();
                }
                else
                    if (dsTreeTemp != null && dsTreeTemp.Tables[0].Rows.Count > 0 && dsCayUserHtai != null && dsCayUserHtai.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < dsTreeTemp.Tables[0].Rows.Count; i++)
                        {
                            string menuid = dsTreeTemp.Tables[0].Rows[i]["MENUID"].ToString();

                            DataRow[] drArr = dsCayUserHtai.Tables[0].Select("MENUID = '" + menuid + "'");
                            if (drArr.Count() < 1)
                            {
                                dsCayUserHtai.Tables[0].ImportRow(dsTreeTemp.Tables[0].Rows[i]);
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void dsResultTREE_vs_dsCayUserHtai()  // so sánh -> ko có đổi màu
        {
            try
            {
                if (dsCayUserHtai == null || dsCayUserHtai.Tables[0].Rows.Count < 1)
                {
                    dsCayUserHtai = dsTreeTemp.Clone();
                }

                dsColor = dsResultTREE.Clone();
                for (int i = 0; i < dsResultTREE.Tables[0].Rows.Count; i++)
                {
                    string menuid = dsResultTREE.Tables[0].Rows[i]["MENUID"].ToString();

                    DataRow[] drArr = dsCayUserHtai.Tables[0].Select("MENUID = '" + menuid + "'");
                    if (drArr.Count() < 1)
                    {
                        dsColor.Tables[0].ImportRow(dsResultTREE.Tables[0].Rows[i]);
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void btnThem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                bool check = false;

                if (itselGoc == null)
                {
                    return;
                }

                dsTreeTemp.Clear();
                intMENUIDtreeItemSel = Convert.ToInt64(itselGoc.Tag.ToString());

                Find_Parent(intMENUIDtreeItemSel);
                Find_Children(intMENUIDtreeItemSel);
                dsTreeTemp_vs_dsCayUserHtai();
                dsResultTREE_vs_dsCayUserHtai();

                Fill_Data_Tree();

                if (dsCayUserHtai != null && dsCayUserHtai.Tables[0].Rows.Count > 0)
                {
                    Fill_Data_Tree_User(dsCayUserHtai);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void btnXoa_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (itselUser == null)
                {
                    return;
                }

                dsXoaItems.Clear();
                intMENUIDtreeItemSel = Convert.ToInt64(itselUser.Tag.ToString());

                DataTable dt = dsResultTREE.Tables[0].Select("MENUID = '" + intMENUIDtreeItemSel.ToString() + "'").CopyToDataTable();

                //lấy item chọn vào dsach xóa
                dsXoaItems.Tables[0].ImportRow(dt.Rows[0]);

                Get_Childrens_to_del(intMENUIDtreeItemSel);
                Del_childrens();

                dsResultTREE_vs_dsCayUserHtai();

                Fill_Data_Tree();

                if (dsCayUserHtai != null && dsCayUserHtai.Tables[0].Rows.Count > 0)
                {
                    Fill_Data_Tree_User(dsCayUserHtai);
                }
                else
                {
                    this.TvUser.Items.Clear();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void TvGoc_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            try
            {
                itselGoc = TvGoc.SelectedItem as TreeViewItem;
                if (itselGoc != null)
                {
                    btnThem.IsEnabled = true;
                    btnXoa.IsEnabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void TvUser_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            try
            {
                itselUser = TvUser.SelectedItem as TreeViewItem;
                if (itselUser != null)
                {
                    btnThem.IsEnabled = false; ;
                    btnXoa.IsEnabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
